package com.fndsoft.zheshangmeap.net;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.os.AsyncTask;

import com.fndsoft.zheshangmeap.component.colog.COLog;
import com.fndsoft.zheshangmeap.data.SessionData;
import com.fndsoft.zheshangmeap.domain.ThreadMessage;
import com.fndsoft.zheshangmeap.net.send.SendService;
import com.fndsoft.zheshangmeap.service.HttpService;
import com.fndsoft.zheshangmeap.util.ConfigUtil;
import com.fndsoft.zheshangmeap.util.ValueUtil;

/**
 * @author carlos carlosk@163.com
 * @version 创建时间：2012-9-30 上午6:09:28 类说明
 */

public class HttpAsyncTask extends
		AsyncTask<ThreadMessage, Integer, HttpReturnMessage> {
	public static final String TAG = HttpService.TAG;
	private static int CONNECTION_TIMEOUT = 15 * 1000;
	public static final String COOKIE = "Cookie";

	@Override
	protected HttpReturnMessage doInBackground(ThreadMessage... params) {
		HttpReturnMessage result = new HttpReturnMessage();

		if (null == params || params.length == 0) {
			result.setResultException(new NullPointerException());
			return result;
		}
		// 处理发送前的数据处理
		ThreadMessage threadMessage = params[0];
		HttpEntity httpEntity = SendService.operateSendData(threadMessage);
		if (ValueUtil.isEmpty(httpEntity)) {
			return result;
		}

		// 添加测试服务器
		COLog.d(ConfigUtil.getBaseUrl()
				+ threadMessage.getOperateCode().getResString());

		httpEntity.setUrl(ConfigUtil.getBaseUrl()
				+ threadMessage.getOperateCode().getResString());

		result.setThreadMessage(threadMessage);

		StringBuffer urlString = new StringBuffer(httpEntity.getUrl());
		Map<String, String> paramMap = httpEntity.getParamMap();
		switch (httpEntity.getHttpType()) {
		case GET:
			getContent(result, urlString, paramMap,
					threadMessage.isNeedUpdateSession());
			break;
		case POST:
			postContent(result, urlString, paramMap,
					threadMessage.isNeedUpdateSession());
			break;
		default:
			break;
		}
		return result;
	}

	@Override
	protected void onPostExecute(HttpReturnMessage result) {
		super.onPostExecute(result);
		// 发送消息给前台
		HttpService.receiveResult(result);
	}

	private void postContent(HttpReturnMessage result, StringBuffer urlString,
			Map<String, String> paramMap, boolean isNeedUpdateSession) {
		debug("url = " + urlString.toString());
		DefaultHttpClient httpClient = null;
		HttpResponse response = null;
		HttpPost httpPost = null;
		String responseData = "";
		String jsonString = "";
		URI path = null;
		try {
			path = new URI(urlString.toString());

			httpClient = new DefaultHttpClient();
			httpPost = new HttpPost(path);
			Set<String> keySet = paramMap.keySet();
			List<NameValuePair> params = new ArrayList<NameValuePair>();

			for (String eachKey : keySet) {
				jsonString = jsonString + eachKey + "=" + paramMap.get(eachKey)
						+ "&";
				String value = paramMap.get(eachKey);
				if (null == value) {
					value = "";
				}
				params.add(new BasicNameValuePair(eachKey, value));
			}

			if (!isNeedUpdateSession) {
				// 设置session
				String session = SessionData.getSession();
				if (ValueUtil.isStrNotEmpty(session)) {
					httpPost.setHeader(COOKIE, session);
					debug("head add:" + COOKIE + "=" + session);
				}
			}

			debug("参数=" + jsonString);
			httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
			// 请求超时
			httpClient.getParams()
					.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
							CONNECTION_TIMEOUT);
			// 响应超时
			httpClient.getParams().setParameter(
					CoreConnectionPNames.SO_TIMEOUT, CONNECTION_TIMEOUT);

			response = httpClient.execute(httpPost);

			if (null == response || response.getStatusLine() == null) {
				return;
			}

			responseData = EntityUtils.toString(response.getEntity(), "UTF-8");
			debug("responseCode=" + response.getStatusLine().getStatusCode());
			debug("responseData =" + responseData);

			if (response.getStatusLine().getStatusCode() == 200) {
				if (isNeedUpdateSession) {
					SessionData.updateSession(httpClient);
				}

				result.setResultContent(responseData);
				result.setSuccess(true);
			}
		} catch (Exception e) {
			result.setResultException(e);
			debug(e.toString());
		}
	}

	private void getContent(HttpReturnMessage result, StringBuffer urlString,
			Map<String, String> paramMap, boolean isNeedUpdateSession) {

		HttpURLConnection conn = null;
		URL url = null;
		try {
			// 拼接后面的get参数
			if (null != paramMap && paramMap.size() > 0) {
				urlString.append("?");
				Set<String> keySet = paramMap.keySet();
				for (String eachKey : keySet) {
					String value = URLEncoder.encode(paramMap.get(eachKey),
							"UTF-8");
					urlString.append(eachKey).append("=").append(value)
							.append("&");
				}
			}

			COLog.d("url:" + urlString.toString());

			url = new URL(urlString.toString());

			conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			conn.setDoOutput(false);
			conn.setDoInput(true);
			conn.setConnectTimeout(6000);
			conn.setRequestProperty("Content-Type",
					"text/xml; charset=\"utf-8\"");

			if (!isNeedUpdateSession) {
				// 设置session
				String session = SessionData.getSession();
				if (ValueUtil.isStrNotEmpty(session)) {
					conn.setRequestProperty(COOKIE, session);
					debug("head add:" + COOKIE + "=" + session);
				}
			}

			conn.connect();
			int code = conn.getResponseCode();
			if (code == 200) {
				if (isNeedUpdateSession) {
					SessionData.updateSession(conn);
				}

				if (result.getThreadMessage().isRequestFile()) {
					byte[] resultByteArr = readByteArray(conn);
					result.setResultByteArr(resultByteArr);
				} else {
					String content = readByteContent(conn);
					result.setResultContent(content);
				}
				result.setSuccess(true);
			}

			conn.getInputStream().close();
			conn.disconnect();
		} catch (IOException e) {
			result.setResultException(e);
		} catch (Exception e) {
			result.setResultException(e);
		}
	}

	/**
	 * 从conn里读取数据,转换成字符串
	 * 
	 * @author carlos carlosk@163.com
	 * @version 创建时间：2012-4-7 下午2:06:16
	 * @param connection
	 * @return
	 * @throws IOException
	 */
	private String readByteContent(HttpURLConnection connection)
			throws IOException {
		InputStream in = connection.getInputStream();
		BufferedReader reader = new BufferedReader(new InputStreamReader(in,
				"utf-8"));
		StringBuffer contentStringBuffer = new StringBuffer();
		String temp = null;
		while ((temp = reader.readLine()) != null) {
			contentStringBuffer.append(temp);
		}
		reader.close();
		return contentStringBuffer.toString();
	}

	/**
	 * 从conn里读取数据,转换成字节数组
	 * 
	 * @author LiangXiangJu
	 * @creationTime 2014-3-24 下午5:29:50
	 * @version
	 * @param connection
	 * @return
	 * @throws IOException
	 */
	private byte[] readByteArray(HttpURLConnection connection)
			throws IOException {
		byte[] byt = null;
		InputStream in = connection.getInputStream();
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();

		byte[] buf = new byte[1024];
		int len;
		while ((len = in.read(buf)) != -1) {
			outStream.write(buf, 0, len);
		}
		byt = outStream.toByteArray();
		outStream.close();
		return byt;
	}

	public void debug(String msg) {
		String tag = this.getClass().getSimpleName();
		COLog.d(tag, msg);
	}

}
